package cn.farm.farm.Service.CommonService;

import cn.farm.farm.Config.Common.CommonDto.MessageExecution;
import cn.farm.farm.Config.Common.CommonDto.PageHelperResult;
import cn.farm.farm.Config.Common.CommonDto.Result;
import cn.farm.farm.Config.Common.CommonEnums.MessageStateEnum;
import cn.farm.farm.Config.Common.CommonException.LikeException;
import cn.farm.farm.Entity.Common.Message;
import cn.farm.farm.Mapper.CommonMapper.MessagetMapper;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class MessageService {

    @Autowired
    private MessagetMapper messagetMapper;

    public Result<PageHelperResult> foundByName(String keyword, Integer pageNum, Integer pageSize) {
        //声明数据变量
        Result<PageHelperResult> result;//返回信息
        MessageExecution execution;//返回Data
        PageHelperResult<Message> pageHelperResult = new PageHelperResult<>();
        try{
            //查询所有数据
            List<Message> list = messagetMapper.likeSelect(keyword);
            Integer all = list.size();
            Integer Size;
            if(all == 0){
                throw new LikeException("num为空");
            }
            if(pageNum<=(Integer)(all/pageSize)){
                Size = pageSize;
            }else{
                Size = all - (pageNum-1)*pageSize;
            }
            //查询数据库
            PageHelper.startPage(pageNum,pageSize);//从第几条数据开始，每页显示多少条数据
            list = messagetMapper.likeSelect(keyword);
            pageHelperResult.setList(list);
            pageHelperResult.setName(keyword);
            pageHelperResult.setPageNumber(Size);
            pageHelperResult.setNumber(all);
            if(list.size() == 0){
                throw new LikeException("查询不到任何信息");
            }

            //构造返回变量
            execution = new MessageExecution(MessageStateEnum.SUCCESS);
            result = new Result(execution.getState(),pageHelperResult,execution.getStateInfo());

            return result;
        }catch(LikeException l){
            throw new LikeException("Login inner error:" + l.getMessage());
        }
    }

    public List<Message> foundHotMessage(Set<String> set) {
        List<Message> list = new ArrayList<>();
        for (String s : set) {
            list.add(messagetMapper.foundHotProtect(Integer.parseInt(s)));
        }
        return list;
    }
}
